package com.lastcode6175.bluetoothremotecontrol

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class BluetoothViewModel(
) : ViewModel() {

    private var bluetoothService: BluetoothServiceApi? = null

    private val _state = MutableStateFlow(BluetoothConnectionState.DISCONNECTED)
    val state = _state.asStateFlow()

    private val _availableDevices = MutableStateFlow<List<BluetoothDeviceInfo>>(emptyList())
    val availableDevices = _availableDevices.asStateFlow()
    
    // 鼠标控制模式
    private val _mouseControlMode = MutableStateFlow(MouseControlMode.NONE)
    val mouseControlMode = _mouseControlMode.asStateFlow()

    private val _connectedDeviceName = MutableStateFlow("")
    val connectedDeviceName = _connectedDeviceName.asStateFlow()

    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage = _errorMessage.asStateFlow()

    private val _permissionRequest = MutableSharedFlow<Array<String>>()
    val permissionRequest = _permissionRequest.asSharedFlow()

    fun checkPermissions() {
        bluetoothService?.checkPermissions()
    }

    fun setBluetoothService(service: BluetoothServiceApi) {
        this.bluetoothService = service
        Log.d("BluetoothViewModel", "BluetoothService set")
        viewModelScope.launch {
            bluetoothService?.state?.collect {
                _state.value = it
                Log.d("BluetoothViewModel", "State updated: $it")
            }
        }
        viewModelScope.launch {
            bluetoothService?.availableDevices?.collect {
                _availableDevices.value = it
                Log.d("BluetoothViewModel", "Available devices updated: ${it.size} devices")
            }
        }
        viewModelScope.launch {
            bluetoothService?.connectedDeviceName?.collect {
                _connectedDeviceName.value = it
                Log.d("BluetoothViewModel", "Connected device name updated: $it")
            }
        }
        viewModelScope.launch {
            bluetoothService?.errorMessage?.collect {
                _errorMessage.value = it
                Log.d("BluetoothViewModel", "Error message updated: $it")
            }
        }
        viewModelScope.launch {
            bluetoothService?.permissionRequest?.collect {
                _permissionRequest.emit(it)
                Log.d("BluetoothViewModel", "Permission request emitted")
            }
        }
    }

    fun scanDevices() {
        Log.d("BluetoothViewModel", "scanDevices called")
        bluetoothService?.scanDevices()
    }

    fun connectToDevice(deviceInfo: BluetoothDeviceInfo) {
        Log.d("BluetoothViewModel", "connectToDevice called with ${deviceInfo.name}")
        // 如果当前已连接到其他设备，先记录状态变更
        if (_state.value == BluetoothConnectionState.CONNECTED && 
            _connectedDeviceName.value.isNotEmpty() && 
            _connectedDeviceName.value != deviceInfo.name) {
            Log.d("BluetoothViewModel", "切换设备: 从 ${_connectedDeviceName.value} 到 ${deviceInfo.name}")
        }
        bluetoothService?.connectToDevice(deviceInfo)
    }

    fun sendAsciiKeyPress(key: Char) {
        bluetoothService?.sendAsciiKeyPress(key)
    }

    fun sendMouseMove(dx: Int, dy: Int) {
        bluetoothService?.sendMouseMove(dx, dy)
    }

    fun sendMouseClick() {
        bluetoothService?.sendMouseClick()
    }
    
    fun sendMouseScroll(amount: Int) {
        // 正值向下滚动，负值向上滚动
        bluetoothService?.sendMouseScroll(amount)
    }
    
    fun setMouseControlMode(mode: MouseControlMode) {
        _mouseControlMode.value = mode
    }

    fun sendDpad(direction: ConsumerControlCode) {
        bluetoothService?.sendDpad(direction)
    }

    fun sendOkKey() {
        bluetoothService?.sendOkKey()
    }

    fun sendPowerKey() {
        bluetoothService?.sendPowerKey()
    }

    fun sendHomeKey() {
        bluetoothService?.sendHomeKey()
    }

    fun sendVoiceAssistant() {
        bluetoothService?.sendVoiceAssistant()
    }

    fun sendBackKey() {
        bluetoothService?.sendBackKey()
    }

    fun sendVolumeUp() {
        bluetoothService?.sendVolumeUp()
    }

    fun sendVolumeDown() {
        bluetoothService?.sendVolumeDown()
    }

    fun sendMute() {
        bluetoothService?.sendMute()
    }

    fun sendBackspace() {
        bluetoothService?.sendBackspace()
    }

    fun sendEnter() {
        bluetoothService?.sendEnter()
    }

    fun Char.isAscii(): Boolean {
        return this.code in 0..127
    }

    fun clearErrorMessage() {
        bluetoothService?.clearErrorMessage()
    }
}


